<template>
  <div v-loading="loading">
    <table class="table table-bordered mt-3 mb-1">
      <tbody>
        <tr>
          <td colspan="10" class="font-weight-bold" data-font-bold="true">
            用电信息
            <el-button type="text" v-if="!isViewMode" class="py-0" @click="handlerEdit">
              <i class="fa fa-edit"></i>
            </el-button>
          </td>
        </tr>
        <tr>
          <td width="18%" colspan="2">户号(06开头账号)</td>
          <td width="20%" colspan="2">开户地址</td>
          <td width="20%" colspan="2">联系电话</td>
          <td width="16%" colspan="2">开户户名</td>
          <td width="16%">缴费日期</td>
          <td width="10%">缴费金额</td>
        </tr>
        <tr v-if="!tableData.length">
          <td colspan="2">-</td>
          <td colspan="2">-</td>
          <td colspan="2">-</td>
          <td colspan="2">-</td>
          <td>-</td>
          <td>-</td>
        </tr>
        <tr v-for="(item, index) of tableData" :key="index">
          <td colspan="2" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
            {{ item.ele_table_no || '-' }}
          </td>
          <td colspan="2" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
            {{ item.ele_table_address || '-' }}
          </td>
          <td colspan="2" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
            {{ item.ele_table_phone || '-' }}
          </td>
          <td colspan="2" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
            {{ item.ele_table_account || '-' }}
          </td>
          <td>{{ $utils.dateFormat(item.ele_pay_time, 'yyyy-MM-dd') || '-' }}</td>
          <td>{{ item.ele_pay_fee || '-' }}</td>
        </tr>
      </tbody>
    </table>

    <el-dialog
      :visible.sync="visible"
      :close-on-click-modal="false"
      append-to-body
      title="修改用电信息"
      width="1000px"
    >
      <table class="table table-bordered mt-3 mb-1">
        <tbody>
          <tr>
            <td width="19%">户号(06开头账号)</td>
            <td width="15%">开户地址</td>
            <td width="15%">联系电话</td>
            <td width="15%">开户户名</td>
            <td width="15%">缴费日期</td>
            <td width="15%">缴费金额</td>
            <td width="6%">操作</td>
          </tr>
          <tr v-for="(p, index) of editData" :key="index">
            <td class="report-input-td" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
              <el-input v-model="p.ele_table_no" placeholder="户号(06开头账号)"></el-input>
            </td>
            <td class="report-input-td" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
              <el-input v-model="p.ele_table_address" placeholder="开户地址"></el-input>
            </td>
            <td class="report-input-td" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
              <el-input v-model="p.ele_table_phone" placeholder="联系电话"></el-input>
            </td>
            <td class="report-input-td" v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
              <el-input v-model="p.ele_table_account" placeholder="开户户名"></el-input>
            </td>
            <td class="report-input-td">
              <el-date-picker
                v-model="p.ele_pay_time"
                class="w-100"
                type="date"
                placeholder="缴费日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
            <td class="report-input-td">
              <el-input v-model="p.ele_pay_fee" type="number" placeholder="缴费金额"></el-input>
            </td>
            <td v-if="index % 3 === 0" :rowspan="index % 3 === 0 ? 3 : 1">
              <el-button
                class="td-inner-btn text-danger"
                type="text"
                @click="deleteData(p.credit_ele_table_id, index)"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </td>
          </tr>
        </tbody>
      </table>
      <el-button-group class="mb-2 mt-1">
        <el-button size="small" @click="editRowAdd">
          <i class="fa fa-indent"></i>
          新增电表
        </el-button>
      </el-button-group>
      <div class="text-center">
        <el-button type="primary" @click="saveData" :loading="saveLoading" style="min-width: 100px">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getResultArray } from '@/gov/components/creditFile/index'
export default {
  components: {},
  props: {
    queryId: {
      type: String,
      default: '',
    },
    farmId: {
      type: String,
      require: true,
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      visible: false,
      saveLoading: false,
      tableName: 'datum_customer_ele_table',
      tableData: [],
      electrics: [],
      editData: [],
    }
  },
  computed: {
    isViewMode() {
      return this.viewMode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.getData()
      },
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    getData() {
      this.editData = []
      this.tableData = []
      this.loading = true
      const params = {
        'customer_related_id.eq': this.queryId,
        subKey: 'datum_customer_ele_table_detail.credit_ele_table_id',
      }
      this.$api
        .getData(this.$serviceName, this.tableName, params, {
          create_time: 'asc',
        })
        .then(res => {
          this.electrics = getResultArray(res)
          this.electrics.forEach(item => {
            const detail = item.datum_customer_ele_table_detail
            this.editData.push({
              ...item,
              ele_pay_fee: (detail && detail[0] && detail[0].ele_pay_fee) || '',
              ele_pay_time: (detail && detail[0] && detail[0].ele_pay_time) || '',
              datum_customer_ele_table_detail_id:
                (detail && detail[0] && detail[0].datum_customer_ele_table_detail_id) || '',
            })
            this.editData.push({
              ...item,
              ele_pay_fee: (detail && detail[1] && detail[1].ele_pay_fee) || '',
              ele_pay_time: (detail && detail[1] && detail[1].ele_pay_time) || '',
              datum_customer_ele_table_detail_id:
                (detail && detail[1] && detail[1].datum_customer_ele_table_detail_id) || '',
            })
            this.editData.push({
              ...item,
              ele_pay_fee: (detail && detail[2] && detail[2].ele_pay_fee) || '',
              ele_pay_time: (detail && detail[2] && detail[2].ele_pay_time) || '',
              datum_customer_ele_table_detail_id:
                (detail && detail[2] && detail[2].datum_customer_ele_table_detail_id) || '',
            })
          })
          this.editData.forEach(item => {
            this.tableData.push({ ...item })
          })
        })
        .catch(res => {
          this.$message.error(`请求电表信息失败${res}`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    saveData() {
      let data = {
        masterData: {},
        slaveData: [],
      }
      let dataArray = []
      let j = 1
      for (let index = 0; index < this.editData.length; index++) {
        const item = this.editData[index]
        if (index % 3 === 0) {
          const temp = {
            ele_table_no: item.ele_table_no,
            ele_table_address: item.ele_table_address,
            ele_table_phone: item.ele_table_phone,
            ele_table_account: item.ele_table_account,
          }
          if (item.credit_ele_table_id) {
            temp.credit_ele_table_id = item.credit_ele_table_id
          }
          data.masterData = temp
        }
        const eleFee = {
          ele_pay_time: item.ele_pay_time,
          ele_pay_fee: item.ele_pay_fee,
        }
        if (item.datum_customer_ele_table_detail_id) {
          eleFee.datum_customer_ele_table_detail_id = item.datum_customer_ele_table_detail_id
        }
        if (j >= 3) {
          j = 1
          if (item.ele_pay_time) {
            data.slaveData.push(eleFee)
          }
          if (data.masterData.credit_ele_table_id && !data.masterData.ele_table_no) {
            return this.$message.warning('请输入电表号')
          }
          if (data.masterData.ele_table_no) {
            dataArray.push(data)
          }
          data = {
            masterData: {},
            slaveData: [],
          }
        } else {
          if (item.ele_pay_time) {
            data.slaveData.push(eleFee)
          }
          j++
        }
      }
      if (!dataArray.length) {
        return
      }
      const promiseAarry = []
      this.saveLoading = true
      for (let p of dataArray) {
        p.masterData.customer_related_id = this.queryId
        p.masterData.customer_id = this.farmId
        const formData = {
          masterTableInfo: JSON.stringify(p.masterData),
          masterTableName: 'datum_customer_ele_table',
          slaveTableInfo: JSON.stringify(p.slaveData),
          slaveTableName: 'datum_customer_ele_table_detail',
        }
        if (p.masterData.credit_ele_table_id) {
          promiseAarry.push(this.$api.relatedUpdate(this.$serviceName, formData))
        } else {
          promiseAarry.push(this.$api.relatedBatch(this.$serviceName, formData))
        }
      }
      Promise.all(promiseAarry)
        .then(() => {
          this.$message.success('保存成功')
          this.getData()
          this.visible = false
        })
        .catch(err => this.$message.error(`保存失败${err}`))
        .finally(() => {
          this.saveLoading = false
        })
    },
    handlerEdit() {
      this.editData = []
      this.visible = true
      this.electrics.forEach(item => {
        const detail = item.datum_customer_ele_table_detail
        this.editData.push({
          ...item,
          ele_pay_fee: (detail && detail[0] && detail[0].ele_pay_fee) || '',
          ele_pay_time: (detail && detail[0] && detail[0].ele_pay_time) || '',
          datum_customer_ele_table_detail_id:
            (detail && detail[0] && detail[0].datum_customer_ele_table_detail_id) || '',
        })
        this.editData.push({
          ...item,
          ele_pay_fee: (detail && detail[1] && detail[1].ele_pay_fee) || '',
          ele_pay_time: (detail && detail[1] && detail[1].ele_pay_time) || '',
          datum_customer_ele_table_detail_id:
            (detail && detail[1] && detail[1].datum_customer_ele_table_detail_id) || '',
        })
        this.editData.push({
          ...item,
          ele_pay_fee: (detail && detail[2] && detail[2].ele_pay_fee) || '',
          ele_pay_time: (detail && detail[2] && detail[2].ele_pay_time) || '',
          datum_customer_ele_table_detail_id:
            (detail && detail[2] && detail[2].datum_customer_ele_table_detail_id) || '',
        })
      })
      if (this.editData.length < 6) {
        this.addTemp(6 - this.editData.length)
      }
    },
    addTemp(len) {
      for (let i = 0; i < len; i++) {
        this.editData.push({})
      }
    },
    editRowAdd() {
      this.addTemp(3)
    },
    deleteItem(index) {
      this.editData.splice(index, 3)
    },
    deleteData(id, index) {
      if (!id) {
        this.deleteItem(index)
        return
      }
      this.$utils
        .msgbox({
          message: '确定删除?',
          beforeClose: () =>
            this.$api.relatedDelete(this.$serviceName, {
              masterTableInfo: JSON.stringify({ credit_ele_table_id: id }),
              masterTableName: 'datum_customer_ele_table',
              slaveTableName: 'datum_customer_ele_table_detail',
            }),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/gov/components/creditFile/style.scss';
</style>
